//
//  AppDelegate.m
//  EnvironmentalProtection
//
//  Created by HCreater on 2018/5/22.
//  Copyright © 2018年 HCreater. All rights reserved.
//

#import "AppDelegate.h"

#import "LoadingViewController.h"

#if defined(DEBUG)||defined(_DEBUG)
#import "JPFPSStatus.h"
#import <FBMemoryProfiler/FBMemoryProfiler.h>
#import <FBRetainCycleDetector/FBRetainCycleDetector.h>
#import "CacheCleanerPlugin.h"
#import "RetainCycleLoggerPlugin.h"
#endif

@interface AppDelegate ()

@end


@implementation AppDelegate
{
#if defined(DEBUG)||defined(_DEBUG)
    FBMemoryProfiler *memoryProfiler;
#endif
}

#pragma mark- 获取appdelegate
+ (AppDelegate *)sharedDelegate
{
    return (AppDelegate *)[[UIApplication sharedApplication] delegate];
}

#pragma mark - 调试(DEBUG)模式
- (void)_configDebugModelTools
{
#if defined(DEBUG)||defined(_DEBUG)
    /// 显示FPS
    [[JPFPSStatus sharedInstance] open];
    
    /// 内存分析+通过Runtime监测循环引用+跟踪oc对象的分配情况
    NSArray *filters = @[FBFilterBlockWithObjectIvarRelation([UIView class], @"_subviewCache"),
                         FBFilterBlockWithObjectIvarRelation([UIPanGestureRecognizer class], @"_internalActiveTouches")];
    FBObjectGraphConfiguration *configuration =
    [[FBObjectGraphConfiguration alloc] initWithFilterBlocks:filters
                                         shouldInspectTimers:NO];
    memoryProfiler = [[FBMemoryProfiler alloc] initWithPlugins:@[[CacheCleanerPlugin new],
                                                                 [RetainCycleLoggerPlugin new]]
                              retainCycleDetectorConfiguration:configuration];
    [memoryProfiler enable];
#endif
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    
    NSLog(@"Window Frame : %@", NSStringFromCGRect([UIScreen mainScreen].bounds));
    
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
    
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    
    LoadingViewModel* vm = [[LoadingViewModel alloc] initWithParams:@{}];
    LoadingViewController* vc = [[LoadingViewController alloc] initWithViewModel:vm];
    self.window.rootViewController = vc;
    
    [self.window makeKeyAndVisible];
    
    [UIManager sharedUIManager];
    
    [[UMManager sharedUMManager] init:self launchOptions:launchOptions];
    
    //设置语言
    [self setPreferredLanguage];

    // 微信配置
    [WXApi registerApp:APPID_WX];
    
    return YES;
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.

    NSLog(@"applicationDidEnterBackground");
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.

    NSLog(@"applicationWillEnterForeground");
    
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.

    NSLog(@"applicationDidBecomeActive");
    
    //做延迟判断
    dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0/*延迟执行时间*/ * NSEC_PER_SEC));

    dispatch_after(delayTime, dispatch_get_main_queue(), ^{
        if ([DataManager sharedDataManager].isInThirdLogin)
        {
            [[NSNotificationCenter defaultCenter] postNotificationName:Notify_WXResp object:@{@"ErrorCode":@(-100), @"ErrorTip":@"微信授权中断"}];
        }
    });
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    if ([[UMManager sharedUMManager] openURL:url sourceApplication:sourceApplication annotation:annotation])
    {
        return YES;
    }

    if ([sourceApplication isEqualToString:@"com.tencent.xin"])
    {
        return [WXApi handleOpenURL:url delegate:self];
    }

    return YES;
}

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options{

    if ([options[UIApplicationOpenURLOptionsSourceApplicationKey] isEqualToString:@"com.tencent.xin"])
    {
        return [WXApi handleOpenURL:url delegate:self];
    }

    return YES;
}

//iOS10以下使用这个方法接收通知
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    [[UMManager sharedUMManager] didReceiveRemoteNotification:userInfo];
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
{
    //Apns注册成功，该方法没有没有变化。
    NSString* strDevToken = [[[[deviceToken description] stringByReplacingOccurrencesOfString: @"<" withString: @""] stringByReplacingOccurrencesOfString: @">" withString: @""] stringByReplacingOccurrencesOfString: @" " withString: @""];

    NSLog(@"DevToken : %@", strDevToken);

    [UMManager sharedUMManager].devToken = strDevToken;
}

#pragma mark -
#pragma mark wx回调
- (void)onResp:(BaseResp*)resp
{
    if ([resp isKindOfClass:[SendAuthResp class]]) {   //授权登录的类。
        if (resp.errCode == 0) {  //成功。
            //这里处理回调的方法 。 通过代理吧对应的登录消息传送过去。

            SendAuthResp *resp2 = (SendAuthResp *)resp;
            [[NSNotificationCenter defaultCenter] postNotificationName:Notify_WXResp object:resp2.code];

        }else{ //失败
            NSLog(@"error %@",resp.errStr);
            [[NSNotificationCenter defaultCenter] postNotificationName:Notify_WXResp object:@{@"ErrorCode":@(-200), @"ErrorTip":@"微信授权失败"}];

            UIAlertController* alertC = [UIAlertController alertControllerWithTitle:USLocalizedString(@"登录失败", nil) message:[NSString stringWithFormat:@"reason : %@",resp.errStr] preferredStyle:UIAlertControllerStyleAlert];

            UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:nil];
            [alertC addAction:okAction];

            [self.window.rootViewController presentViewController:alertC animated:YES completion:^{

            }];
        }
    }
    else if([resp isKindOfClass:[PayResp class]])
    {
        //支付返回结果，实际支付结果需要去微信服务器端查询

        [[WTPayManager shareWTPayManager] onResp:resp];

        //        NSString *strMsg;
        //
        //        switch (resp.errCode) {
        //            case WXSuccess:
        //                strMsg = @"支付结果：成功！";
        //                NSLog(@"支付成功－PaySuccess，retcode = %d", resp.errCode);
        //                break;
        //
        //            default:
        //                strMsg = [NSString stringWithFormat:@"支付结果：失败！retcode = %d, retstr = %@", resp.errCode,resp.errStr];
        //                NSLog(@"错误，retcode = %d, retstr = %@", resp.errCode,resp.errStr);
        //                break;
        //        }
    }
    else if ([resp isKindOfClass:[WXLaunchMiniProgramResp class]])
    {
        WXLaunchMiniProgramResp* wmpResp = resp;
        NSString *string = wmpResp.extMsg;
        // 对应JsApi navigateBackApplication中的extraData字段数据
    }
}

- (void)setPreferredLanguage
{
    // 设置默认语言
    if (![[NSUserDefaults standardUserDefaults] objectForKey:UserDefaultKey_AppLanguage]) {
        NSArray *languages = [NSLocale preferredLanguages]; //系统偏好语言
        NSString *language = languages.firstObject;
        if ([language hasPrefix:@"zh-Hans"]) {
            [[NSUserDefaults standardUserDefaults] setObject:@"zh-Hans" forKey:UserDefaultKey_AppLanguage];
        }
        else if ([language hasPrefix:@"zh-Hant"]) {
            [[NSUserDefaults standardUserDefaults] setObject:@"zh-Hant" forKey:UserDefaultKey_AppLanguage];
        }
        else if ([language hasPrefix:@"en"]) {
            [[NSUserDefaults standardUserDefaults] setObject:@"en" forKey:UserDefaultKey_AppLanguage];
        }
    }

    NSString *language = [[NSUserDefaults standardUserDefaults] objectForKey:UserDefaultKey_AppLanguage];
    [NSBundle setLanguage:language];

    if ([language hasPrefix:@"zh-Hans"]) {
        [[NSUserDefaults standardUserDefaults] setObject:@"zh-Hans" forKey:UserDefaultKey_AppLanguage];
        UM_appLanguageV2 = @"CH";
    }
    else if ([language hasPrefix:@"zh-Hant"]) {
        [[NSUserDefaults standardUserDefaults] setObject:@"zh-Hant" forKey:UserDefaultKey_AppLanguage];
        UM_appLanguageV2 = @"CHS";
    }
    else if ([language hasPrefix:@"en"]) {
        [[NSUserDefaults standardUserDefaults] setObject:@"en" forKey:UserDefaultKey_AppLanguage];
        UM_appLanguageV2 = @"EN";
    }
}

- (void)resetWindowRootViewController
{
    LoadingViewModel* vm = [[LoadingViewModel alloc] initWithParams:@{}];
    LoadingViewController* vc = [[LoadingViewController alloc] initWithViewModel:vm];

    self.window.rootViewController = vc;
}


@end
